<template>
  <view
      class="__slider"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @tap="handleTap"
      :style="sliderStyle"
  >
    <slot></slot> <!-- 插槽用于插入滑动内容 -->
  </view>
</template>

<script>
export default {
  name: "slider-item",
  data() {
    return {
      slotElementWidth: 0, // 插槽元素宽度
      slotElementHeight: 0, // 插槽元素高度
      startX: 0, // 触摸开始的X坐标
      startY: 0, // 触摸开始的Y坐标
      translateX: 0, // 当前移动的X偏移
      threshold: 100, // 滑动阈值
      isSliding: false, // 是否正在滑动
      slidingY: false // 是否正在纵向滑动
    };
  },
  computed: {
    sliderStyle() {
      return {
        transform: `translateX(${this.translateX}px)`,
        transition: this.isSliding ? 'none' : 'transform 0.25s ease'
      };
    }
  },
  mounted() {
    this.getSlotElementSize(); // 组件挂载后获取插槽元素的尺寸
  },
  methods: {
    handleTap(e) {
      this.$emit('click', e);
    },
    getSlotElementSize() {
      let dom = uni.createSelectorQuery().in(this.$root);
      dom.select(".__slider").boundingClientRect()
      dom.exec((data) => {
        this.slotElementWidth = data[0].width;
        this.slotElementHeight = data[0].height;
        this.threshold = this.slotElementWidth * 0.25; // 设置滑动阈值
      })

    },
    handleTouchStart(event) {
      this.startX = event.touches[0].clientX;
      this.startY = event.touches[0].clientY;
    },
    handleTouchMove(event) {
      const moveX = event.touches[0].clientX - this.startX;
      const moveY = event.touches[0].clientY - this.startY;
      // 判断是否为纵向滑动
      if (!this.isSliding && Math.abs(moveY) > 5) {
        this.startX = event.touches[0].clientX;
        this.slidingY = true;
        return;
      }
      // 判断是否达到滑动阈值
      if (!this.slidingY && Math.abs(moveX) <= this.threshold && Math.abs(moveX) > this.threshold * 0.1) {
        this.translateX = moveX; // 设置当前的X偏移
        event.preventDefault(); // 阻止默认事件
        this.isSliding = true;
      }
    },
    handleTouchEnd() {
      // 判断是否达到滑动阈值
      if (Math.abs(Math.abs(this.translateX) - this.threshold) < this.threshold * 0.2) {
        this.$emit('swipe', this.translateX > 0 ? 'right' : 'left'); // 触发滑动事件
      }
      // 回弹
      this.translateX = 0; // 或者根据需要调整回弹效果
      this.isSliding = false;
      this.slidingY = false;
    }
  }
};
</script>

<style scoped>
.__slider {
  touch-action: pan-y; /* 允许上下滑动 */
  overflow: hidden;
  width: 100%; /* 拖动区域宽度 */
  height: 100px;
}
</style>
